<?php

namespace App\Kuafu\WaiMai\Command;

use App\Kuafu\WaiMai\Channel\BaseWaiMai;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Kuafu\WaiMai\Model\WaiMaiShopMappingModel;
use App\Kuafu\WaiMai\Service\BaseWaiMaiOrderService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class WaiMaiOrderRepair extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'waiMai-orderRepair {shopId?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '外卖订单自动修复补单';

    /**
     * Create a new command instance.
     *
     * @return void//
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command
     *
     * @return int
     */
    public function handle()
    {
        $argShopId = (int)$this->argument('shopId');

        // 所有店铺轮询
        WaiMaiShopMappingModel::query()
                              ->when($argShopId, function ($query) use ($argShopId) {
                                  $query->where('shopId', $argShopId);
                              })
                              ->whereIn('sourceType', [WaiMaiDBEnum::SOURCE_TYPE_MT_WM, WaiMaiDBEnum::SOURCE_TYPE_ELM])
                              ->select(['sourceType', 'shopId', 'thirdShopId'])
                              ->get()
                              ->each(function ($item) {
                                  $waiMaiObj = BaseWaiMai::getIns($item->sourceType, $item->shopId, $item->thirdShopId);
                                  $orders    = (array)$waiMaiObj->getErrorOrders();
                                  if (!$orders['status'] || !$orders['data']) {
                                      return;
                                  }
                                  $orderIds = $orders['data'];

                                  foreach ($orderIds as $orderId) {
                                      $detail = $waiMaiObj->getOrderDetail($orderId);

                                      if (!$detail['status'] || !isset($detail['data']['createdAt'])) {
                                          return;
                                      }

                                      // 仅处理超过30秒的异常订单
                                      if (time() - $detail['data']['createdAt'] < 30) {
                                          return;
                                      }

                                      $dbOrderStatus = BaseWaiMaiOrderService::getIns($item->sourceType)
                                                                             ->convertOrderStatus($detail['data']['orderStatus']);
                                      if ($dbOrderStatus >= WaiMaiDBEnum::ORDER_STATUS_2) {
                                          return; // 时间差，已处理
                                      }

                                      Log::info('WaiMaiOrderRepair in:' . $orderId);
                                      dump('WaiMaiOrderRepair in:' . $orderId);

                                      // 判断下本地是不是有
                                      if (WaiMaiOrderModel::suffix($item->shopId)->where('orderId', $orderId)->count()) {

                                          // 本地有，接单
                                          BaseWaiMai::getIns($item->sourceType, $item->shopId)->acceptOrder($orderId);
                                      } else {

                                          // 本地没有，补单
                                          BaseWaiMaiOrderService::getIns($item->sourceType)
                                                                ->setRequestData($detail['oriData'])
                                                                ->init()
                                                                ->createOrder();
                                      }

                                      dump('WaiMaiOrderRepair finish:' . $orderId);
                                      Log::info('WaiMaiOrderRepair finish:' . $orderId);
                                  }
                              });

    }
}
